<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :defaults.sync="defaults"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.steelMeshManage_add" @click="addBtn">新 增</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.steelMeshManage_delete" @click="handleDelete">删 除 </el-button>
        <el-button type="warning" size="small" plain icon="el-icon-download" @click="handleExport">导出 </el-button>
      </template>
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot-scope="{ row, index }" slot="menu">
        <el-button icon="el-icon-view" size="small" type="text" v-if="permission.steelMeshManage_view" @click="rowView(row)">详情</el-button>
        <el-button icon="el-icon-edit" size="small" type="text" v-if="permission.steelMeshManage_edit" @click="rowUpdate(row)">编辑</el-button>
        <el-button icon="el-icon-delete" size="small" type="text" v-if="permission.steelMeshManage_delete" @click="$refs.crud.rowDel(row, index)">删除</el-button>
        <el-button
          v-if="permission.steelMeshManage_enableOrDisable && row.status == 0"
          icon="el-icon-circle-check"
          size="small"
          type="text"
          @click.stop="handleEnableOrDisable(row, 'enable')"
          v-preventReClick
          >启用
        </el-button>
        <el-button
          v-if="permission.steelMeshManage_enableOrDisable && row.status != 0"
          icon="el-icon-circle-close"
          size="small"
          type="text"
          @click.stop="handleEnableOrDisable(row, 'disable')"
          v-preventReClick
          >禁用
        </el-button>
      </template>
    </avue-crud>
    <el-dialog v-dragDirectives ref="dialog" :title="dialogTitle" append-to-body :visible.sync="showDialog" :close-on-click-modal="false" top="5vh" @close="closeDialog">
      <div class="sail-header-dialog-content">
        <avue-form ref="basicInfo" v-if="showDialog" v-model="form" :option="dialogOption"></avue-form>
        <el-tabs type="border-card" v-if="showDialog" v-model="tabsIndex">
          <el-tab-pane label="专业信息" name="1">
            <avue-form ref="majorInfo" v-model="form" :option="majorInfoOption">
              <template slot="principalName">
                <el-input placeholder="请选择 负责人员" v-model="form.principalName" class="input-with-select" disabled>
                  <el-button
                    slot="append"
                    icon="el-icon-circle-close"
                    v-if="form.principalName"
                    :disabled="isDisable"
                    @click="
                      form.principalName = '';
                      form.principal = '';
                    "
                  ></el-button>
                  <el-button slot="append" icon="el-icon-search" @click="openPrincipalCommonModal()" :disabled="isDisable"></el-button>
                </el-input>
              </template>
              <template slot="workshopName">
                <el-input placeholder="请选择 所在车间" v-model="form.workshopName" class="input-with-select" disabled>
                  <el-button
                    slot="append"
                    icon="el-icon-circle-close"
                    v-if="form.workshopName"
                    :disabled="isDisable"
                    @click="
                      form.workshopName = '';
                      form.workshopId = '';
                    "
                  ></el-button>
                  <el-button slot="append" icon="el-icon-search" @click="openWorkshopCommonModal()" :disabled="isDisable"></el-button>
                </el-input>
              </template>
              <template slot="lineName">
                <el-input placeholder="请选择 所在产线" v-model="form.lineName" class="input-with-select" disabled>
                  <el-button
                    slot="append"
                    icon="el-icon-circle-close"
                    v-if="form.lineName"
                    :disabled="isDisable"
                    @click="
                      form.lineName = '';
                      form.lineId = '';
                    "
                  ></el-button>
                  <el-button slot="append" icon="el-icon-search" @click="openLineCommonModal()" :disabled="isDisable"></el-button>
                </el-input>
              </template>
              <template slot="inventoryName">
                <el-input placeholder="请选择 存放仓库" v-model="form.inventoryName" class="input-with-select" disabled>
                  <el-button
                    slot="append"
                    icon="el-icon-circle-close"
                    v-if="form.inventoryName"
                    :disabled="isDisable"
                    @click="
                      form.inventoryName = '';
                      form.inventoryId = '';
                    "
                  ></el-button>
                  <el-button slot="append" icon="el-icon-search" @click="openWarehouseCommonModal()" :disabled="isDisable"></el-button>
                </el-input>
              </template>
              <template slot="feederBusName">
                <el-input placeholder="请选择 适用飞达车" v-model="form.feederBusName" class="input-with-select" disabled>
                  <el-button
                    slot="append"
                    icon="el-icon-circle-close"
                    v-if="form.feederBusName"
                    :disabled="isDisable"
                    @click="
                      form.feederBusName = '';
                      form.feederBusId = '';
                    "
                  ></el-button>
                  <el-button slot="append" icon="el-icon-search" @click="openFeederBusCommonModal()" :disabled="isDisable"></el-button>
                </el-input>
              </template>
              <template slot="suitEquipmentName">
                <el-input placeholder="请选择 适用设备" v-model="form.suitEquipmentName" class="input-with-select" disabled>
                  <el-button
                    slot="append"
                    icon="el-icon-circle-close"
                    v-if="form.suitEquipmentName"
                    @click="
                      form.suitEquipmentName = '';
                      form.suitEquipmentId = '';
                    "
                    :disabled="isDisable"
                  ></el-button>
                  <el-button slot="append" icon="el-icon-search" @click="openEquipmentCommonModal()" :disabled="isDisable"></el-button>
                </el-input>
              </template>
            </avue-form>
          </el-tab-pane>
          <el-tab-pane label="购置信息" name="2">
            <avue-form ref="purchaseInfo" v-model="form" :option="purchaseInfoOption">
              <template slot="supplierName">
                <el-input placeholder="请选择 供应商" v-model="form.supplierName" class="input-with-select" disabled>
                  <el-button
                    slot="append"
                    icon="el-icon-circle-close"
                    v-if="form.supplierName"
                    :disabled="isDisable"
                    @click="
                      form.supplierName = '';
                      form.partnerId = '';
                    "
                  ></el-button>
                  <el-button slot="append" icon="el-icon-search" @click="openVendorCommonModal()" :disabled="isDisable"></el-button>
                </el-input>
              </template>
            </avue-form>
          </el-tab-pane>
          <el-tab-pane label="附件信息" name="3">
            <avue-form ref="enclosureInfo" v-model="form" :option="enclosureInfoOption">
              <template slot="PICTURE">
                <div v-if="dialogTitle != '详情' && form.PICTURE">
                  <el-upload
                    class="upload-demo"
                    action="/api/blade-resource/oss/endpoint/put-file-attach"
                    list-type="picture"
                    accept="image/png, image/jpeg, image/jpg"
                    :on-change="changeFile"
                    :headers="headersObj"
                    :on-preview="handlePreview"
                    :before-upload="pictureUploadBefore"
                    :on-success="pictureUploadSuccess"
                    :file-list="pictureList"
                  >
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传png/jpeg/jpg文件</div>
                  </el-upload>
                </div>
                <div v-if="dialogTitle === '详情' && JSON.stringify(form.PICTURE) != '[]'">
                  <el-image style="width: 100px; height: 100px; padding-right: 10px; display: block" :src="form.PICTURE" @click="openPreview(0, form.PICTURE)"></el-image>
                  <el-button type="text" icon="el-icon-download" size="small" @click="handleDownload(form.PICTURE)">下载</el-button>
                </div>
              </template>
              <template slot="INSPECTION">
                <div v-if="dialogTitle != '详情' && form.INSPECTION">
                  <el-upload
                    class="upload-demo"
                    action="/api/blade-resource/oss/endpoint/put-file-attach"
                    list-type="text"
                    accept=".doc,.docx,.pdf"
                    :on-change="changeFile"
                    :headers="headersObj"
                    :before-upload="textUploadBefore"
                    :on-success="inspectionUploadSuccess"
                    :file-list="inspectionList"
                  >
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传doc/docx/pdf文件</div>
                  </el-upload>
                </div>
                <div v-if="dialogTitle === '详情' && JSON.stringify(form.INSPECTION) != '[]'">
                  <div>{{ form.INSPECTIONNAME }}</div>
                  <el-button type="text" icon="el-icon-download" size="small" @click="handleDownload(form.INSPECTION)">下载</el-button>
                </div>
              </template>
              <template slot="CERT">
                <div v-if="dialogTitle != '详情' && form.CERT">
                  <el-upload
                    class="upload-demo"
                    action="/api/blade-resource/oss/endpoint/put-file-attach"
                    list-type="text"
                    accept=".doc,.docx,.pdf"
                    :on-change="changeFile"
                    :headers="headersObj"
                    :before-upload="textUploadBefore"
                    :on-success="certUploadSuccess"
                    :file-list="certList"
                  >
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传doc/docx/pdf文件</div>
                  </el-upload>
                </div>
                <div v-if="dialogTitle === '详情' && JSON.stringify(form.CERT) != '[]'">
                  <div>{{ form.CERTNAME }}</div>
                  <el-button type="text" icon="el-icon-download" size="small" @click="handleDownload(form.CERT)">下载</el-button>
                </div>
              </template>
            </avue-form>
          </el-tab-pane>
          <el-tab-pane label="维保信息" name="4">
            <avue-form ref="maintenanceInfo" v-model="form" :option="maintenanceInfoOption"></avue-form>
          </el-tab-pane>
        </el-tabs>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="dialogTitle === '新增'" type="primary" size="small" @click="submit"> <i class="el-icon-circle-plus-outline"></i><span>保 存</span> </el-button>
        <el-button v-if="dialogTitle === '编辑'" type="primary" size="small" @click="submit"> <i class="el-icon-circle-check"></i><span>修 改</span> </el-button>
        <el-button size="small" @click="showDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
    <export-excel
      :visible="exprotVisible"
      :option="option"
      :page="page"
      :data="exportData"
      name="钢网管理导出"
      :loading="btnLoading"
      @selectData="handleSelectData"
      @close="handleClose"
    ></export-excel>
  </basic-container>
</template>
<script>
import { getSteelMeshList, getDetail, add, remove, equipmentEnable, equipmentDisable } from '@/api/admin/equipment';
import { getAreaTree, getAreaTreeByInventoryId } from '@/api/admin/storage';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import website from '@/config/website';
import exportExcel from '@/components/export-excel';
import { Base64 } from 'js-base64';
import { getToken } from '@/util/auth';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
export default {
  name: 'EquipmentManageEquipment',
  components: {
    CommonModalTemplate,
    exportExcel,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'STELL_MESH_MANAGE',
      exprotVisible: false,
      btnLoading: false,
      exportData: [],
      form: {},
      defaults: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        selection: true,
        menuWidth: 300, //弹框内字段宽度属性
        dialogWidth: 880, //弹框宽度属性
        labelWidth: '110',
        dialogClickModal: false,
        columnBtn: false,
        column: [
          {
            label: '编码',
            prop: 'code',
            search: true
          },
          {
            label: '规格',
            prop: 'specification',
            search: true
          },
          {
            label: '型号',
            prop: 'model'
          },
          {
            label: '适用设备',
            prop: 'suitEquipmentName',
            formatter: (val, value) => {
              if (val.equipmentTool && JSON.stringify(val.equipmentTool) != '{}') {
                return val.equipmentTool.suitEquipmentName;
              }
            }
          },
          {
            label: '状态',
            prop: 'statusValue',
            search: true,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=mes_equipment_tool_status',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '最大使用次数',
            prop: 'maxUsage'
          },
          {
            label: '已使用次数',
            prop: 'timesUsed'
          },
          {
            label: '剩余可用次数',
            prop: 'quantityAvailable',
            formatter: (val, value, label) => {
              if (!val.maxUsage || val.maxUsage == null) {
                return 0;
              } else if (val.timesUsed && Number(val.maxUsage) < Number(val.timesUsed)) {
                return 0;
              } else if (val.maxUsage && Number(val.maxUsage) >= Number(val.timesUsed)) {
                return val.maxUsage - val.timesUsed;
              } else {
                return value;
              }
            }
          },
          {
            label: '上次保养时间',
            prop: 'latestMaintain'
          }
        ]
      },
      dialogTitle: '新增',
      showDialog: false,
      dialogOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '130',
        column: [
          {
            label: '编码',
            prop: 'code',
            rules: [
              {
                required: true,
                message: '请输入编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '名称',
            prop: 'name',
            value: '钢网',
            rules: [
              {
                required: true,
                message: '请输入名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '规格',
            prop: 'specification',
            rules: [
              {
                required: true,
                message: '请输入规格',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      tabsIndex: '1',
      majorInfoOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '130',
        column: [
          {
            label: '型号',
            prop: 'model'
          },
          {
            label: '负责部门',
            prop: 'principalDeptId',
            type: 'tree',
            placeholder: '请选择 负责部门',
            dicUrl: '/api/blade-system/dept/tree',
            props: {
              label: 'title',
              value: 'id'
            }
          },
          {
            label: '负责人员',
            prop: 'principalName'
          },
          {
            label: '所在车间',
            prop: 'workshopName'
          },
          {
            label: '所在产线',
            prop: 'lineName'
          },
          {
            label: '存放仓库',
            prop: 'inventoryName'
          },
          {
            label: '存放储位',
            prop: 'areaId',
            type: 'tree',
            placeholder: '请选择 存放储位',
            dicData: [],
            props: {
              label: 'title',
              value: 'id'
            }
          },
          {
            label: '适用设备',
            prop: 'suitEquipmentName'
          },
          {
            label: '最大使用次数',
            prop: 'maxUsage',
            rules: [
              {
                required: false,
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  let reg = /^[1-9]\d*$/g;
                  if (value && !reg.test(value)) {
                    callback(new Error('最大使用次数不能小于等于0并且是整数！'));
                  } else {
                    if (String(value).length > 9) {
                      callback(new Error('最大使用次数长度最多为9'));
                    } else {
                      callback();
                    }
                  }
                }
              }
            ]
          },
          {
            label: '张力标准值',
            prop: 'elasticStdValue',
            rules: [
              {
                required: false,
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  let reg = /^[1-9]\d*$/g;
                  if (value && !reg.test(value)) {
                    callback(new Error('张力标准值不能小于等于0并且是整数！'));
                  } else {
                    callback();
                  }
                }
              }
            ]
          },
          {
            label: '张力预警值',
            prop: 'elasticWarnValue',
            rules: [
              {
                required: false,
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  let reg = /^[1-9]\d*$/g;
                  if (value && !reg.test(value)) {
                    callback(new Error('张力预警值不能小于等于0并且是整数！'));
                  } else {
                    callback();
                  }
                }
              }
            ]
          },
          {
            label: '备注',
            prop: 'remarks',
            hide: true,
            type: 'textarea',
            maxlength: 150,
            showWordLimit: true
          }
        ]
      },
      purchaseInfoOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '130',
        column: [
          {
            label: '资产编码',
            prop: 'assetCode'
          },
          {
            label: '购置价格',
            prop: 'procurementPrice',
            rules: [
              {
                required: false,
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  let reg = /^((0{1}\.\d{1,4})|([0-9]\d*\.{1}\d{1,4})|([0-9]+\d*))$/g;
                  if (value && !reg.test(value)) {
                    callback(new Error('购置价格为数字，不能小于0，可保留4位小数'));
                  } else {
                    callback();
                  }
                }
              }
            ]
          },
          {
            label: '购置日期',
            prop: 'procurementDate',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            label: '供应商',
            prop: 'supplierName'
          },
          {
            label: '出厂日期',
            prop: 'manufactureDate',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            label: '入账日期',
            prop: 'keepAccountDate',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            label: '启用日期',
            prop: 'enabledDate',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          }
        ]
      },
      enclosureInfoOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '130',
        column: [
          {
            label: '设备图片',
            prop: 'PICTURE',
            type: 'upload'
          },
          {
            label: '验收报告附件',
            prop: 'INSPECTION',
            type: 'upload'
          },
          {
            label: '投产验证附件',
            prop: 'CERT',
            type: 'upload'
          }
        ]
      },
      maintenanceInfoOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '130',
        column: [
          {
            label: '上次养护时间',
            prop: 'latestMaintain',
            type: 'datetime',
            format: 'yyyy-MM-dd hh:mm:ss',
            valueFormat: 'yyyy-MM-dd hh:mm:ss',
            disabled: true
          }
        ]
      },
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      data: [],
      pictureList: [],
      inspectionList: [],
      certList: []
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.steelMeshManage_add, false),
        viewBtn: this.vaildData(this.permission.steelMeshManage_view, false),
        delBtn: this.vaildData(this.permission.steelMeshManage_delete, false),
        editBtn: this.vaildData(this.permission.steelMeshManage_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    },
    headersObj() {
      let header = { Authorization: `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}` };
      header['Blade-Auth'] = 'bearer ' + getToken();
      return header;
    },
    isDisable() {
      return this.dialogTitle === '详情';
    }
  },
  methods: {
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      for (let i = 0; i < this.selectionList.length; i++) {
        if (this.selectionList[i].status === 4) {
          this.$message({
            type: 'warning',
            message: `编码为${this.selectionList[i].code}的钢网正在领用中，不可删除！`
          });
          return;
        }
        if (this.selectionList[i].status === 1 && this.selectionList[i].timesUsed && Number(this.selectionList[i].timesUsed) > 0) {
          this.$message({
            type: 'warning',
            message: `编码为${this.selectionList[i].code}的钢网存在使用记录且状态为正常，不可删除！`
          });
          return;
        }
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      for (let key in this.query) {
        if (key === 'statusValue') {
          this.query['status'] = this.query[key];
          delete this.query[key];
        }
      }
      getSteelMeshList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.exportData = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    addBtn() {
      this.showDialog = true;
      this.dialogTitle = '新增';
      this.$nextTick(() => {
        this.$refs.basicInfo.allDisabled = false;
        this.$refs.majorInfo.allDisabled = false;
        this.$refs.purchaseInfo.allDisabled = false;
        this.$refs.enclosureInfo.allDisabled = false;
        this.$refs.maintenanceInfo.allDisabled = false;
      });
      this.form['equipmentAttachmentList'] = [];
    },
    openPrincipalCommonModal() {
      this.modalName = 'principalModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择用户管理信息（双击进行选择）',
        url: '/api/blade-system/user/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '用户姓名',
            prop: 'realName',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '所属部门',
            prop: 'deptName',
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '职务',
            prop: 'postName'
          },
          {
            label: '用户平台',
            prop: 'userTypeName'
          }
        ]
      };
    },
    openWorkshopCommonModal() {
      this.modalName = 'workshopModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择车间信息（双击进行选择）',
        url: '/api/mes-admin/workshop/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '车间编码',
            prop: 'code',
            search: true
          },
          {
            label: '车间名称',
            prop: 'name',
            search: true
          }
        ]
      };
    },
    /**
     * 打开产线选择模态框
     */
    openLineCommonModal() {
      this.modalName = 'lineModal';
      this.$refs.commonModalTemplate.showModal();
      let url = '';
      if (this.form.workshopId) {
        url = `/api/mes-product/productionline/page?workshopId=${this.form.workshopId}`;
      } else {
        url = '/api/mes-product/productionline/page';
      }
      this.tableOption = {
        modalTitle: '选择产线信息（双击进行选择）',
        url: url,
        isPage: true,
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        columnDefs: [
          {
            label: '产线名称',
            prop: 'name',
            search: true
          },
          {
            label: '产线编码',
            prop: 'code',
            search: true
          }
        ]
      };
    },
    openWarehouseCommonModal() {
      this.modalName = 'warehouseModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择仓库信息（双击进行选择）',
        url: '/api/mes-admin/inventory/page',
        isPage: true,
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        columnDefs: [
          {
            label: '名称',
            prop: 'name',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '编码',
            prop: 'code',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '仓库类型',
            prop: 'inventoryType',
            search: true,
            type: 'select',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=inventory_type',
            rules: [
              {
                required: true,
                message: '请选择仓库类型',
                trigger: 'blur'
              }
            ]
          }
        ]
      };
    },
    openEquipmentCommonModal() {
      this.modalName = 'equipmentModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择设备信息（双击进行选择）',
        url: '/api/mes-product/ems-equipment/page?type=PRINTER',
        isPage: true,
        rowSelectionType: 'multiple',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        columnDefs: [
          {
            label: '编码',
            prop: 'code',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '名称',
            prop: 'name',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '类型',
            prop: 'categoryName'
          },
          {
            label: '型号',
            prop: 'model'
          },
          {
            label: '规格',
            prop: 'specification',
            rules: [
              {
                required: false,
                message: '请输入规格描述',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '状态',
            prop: 'statusValue'
          }
        ]
      };
    },
    /**
     * 打开供应商选择模态框
     */
    openVendorCommonModal() {
      this.modalName = 'vendorModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择供应商信息（双击进行选择）',
        url: '/api/mes-admin/vendor/page',
        isPage: true,
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        columnDefs: [
          {
            label: '编码',
            prop: 'code',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          }
        ]
      };
    },
    /**
     * 获取选择的模态框行数据
     */
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'principalModal':
          this.form.principal = this._get(rowData, 'id', '');
          this.form.principalName = this._get(rowData, 'realName', '');
          break;
        case 'workshopModal':
          this.form.workshopId = this._get(rowData, 'id', '');
          this.form.workshopName = this._get(rowData, 'name', '');
          break;
        case 'lineModal':
          this.form.lineId = this._get(rowData, 'id', '');
          this.form.lineName = this._get(rowData, 'name', '');
          break;
        case 'warehouseModal':
          this.form.inventoryId = this._get(rowData, 'id', '');
          this.form.inventoryName = this._get(rowData, 'name', '');
          getAreaTreeByInventoryId({ inventoryId: this.form.inventoryId }).then((res) => {
            this.itemData = (res.data.data || []).map((item) => {
              return item;
            });
            const column = this.findObject(this.majorInfoOption.column, 'areaId');
            column.dicData = this.itemData;
          });
          break;
        case 'equipmentModal':
          let equipmentId = [];
          let equipmentName = [];
          this._forEach(rowData, (item) => {
            equipmentId.push(item.id);
            equipmentName.push(item.name);
          });
          this.form.suitEquipmentId = equipmentId.join(',');
          this.form.suitEquipmentName = equipmentName.join(',');
          break;
        case 'vendorModal':
          this.form.partnerId = this._get(rowData, 'id', '');
          this.form.supplierName = this._get(rowData, 'name', '');
          break;
      }
    },
    /**
     * 上传前方法
     */
    pictureUploadBefore(file) {
      console.log(file);
      if (file.name.split('.')[1] != 'png' && file.name.split('.')[1] != 'jpeg' && file.name.split('.')[1] != 'jpg') {
        this.$message({
          type: 'warning',
          message: '只能上传png/jpeg/jpg文件！'
        });
        return false;
      }
    },
    textUploadBefore(file) {
      if (file.name.split('.')[1] != 'doc' && file.name.split('.')[1] != 'docx' && file.name.split('.')[1] != 'pdf') {
        this.$message({
          type: 'warning',
          message: '只能上传dox/docx/pdf文件！'
        });
        return false;
      }
    },
    pictureUploadSuccess(res) {
      if (this.form.equipmentAttachmentList) {
        for (let i = 0; i < this.form.equipmentAttachmentList.length; i++) {
          if ('PICTURE' === this.form.equipmentAttachmentList[i].attachmentType) {
            this.form.equipmentAttachmentList.splice(i, 1);
          }
        }
      } else {
        this.form.equipmentAttachmentList = [];
      }
      this.form.PICTURE = res.data.link;
      this.form['equipmentAttachmentList'].push({
        attachmentId: res.data.attachId,
        link: res.data.link,
        originalName: res.data.originalName,
        attachmentType: 'PICTURE'
      });
    },
    inspectionUploadSuccess(res) {
      if (this.form.equipmentAttachmentList) {
        for (let i = 0; i < this.form.equipmentAttachmentList.length; i++) {
          if ('INSPECTION' === this.form.equipmentAttachmentList[i].attachmentType) {
            this.form.equipmentAttachmentList.splice(i, 1);
          }
        }
      } else {
        this.form.equipmentAttachmentList = [];
      }
      this.form.INSPECTION = res.data.link;
      this.form['equipmentAttachmentList'].push({
        attachmentId: res.data.attachId,
        link: res.data.link,
        originalName: res.data.originalName,
        attachmentType: 'INSPECTION'
      });
    },
    certUploadSuccess(res) {
      if (this.form.equipmentAttachmentList) {
        for (let i = 0; i < this.form.equipmentAttachmentList.length; i++) {
          if ('CERT' === this.form.equipmentAttachmentList[i].attachmentType) {
            this.form.equipmentAttachmentList.splice(i, 1);
          }
        }
      } else {
        this.form.equipmentAttachmentList = [];
      }
      this.form.CERT = res.data.link;
      this.form['equipmentAttachmentList'].push({
        attachmentId: res.data.attachId,
        link: res.data.link,
        originalName: res.data.originalName,
        attachmentType: 'CERT'
      });
    },

    changeFile(files, fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1);
      }
    },
    // /**
    //  * 删除上传文件
    //  */
    // uploadDelete(file, column) {
    //   for (let i = 0; i < this.form.equipmentAttachmentList.length; i++) {
    //     if (column.prop === this.form.equipmentAttachmentList[i].attachmentType) {
    //       this.form.equipmentAttachmentList.splice(i, 1);
    //       this.form[column.prop] = '';
    //       // return;
    //     }
    //   }
    // },
    /**
     * 提交
     */
    async submit() {
      let validData1 = await new Promise((resolve, reject) => {
        this.$refs.basicInfo.validate((valid, done) => {
          if (valid) {
            resolve();
            done();
          }
        });
      });
      let validData2 = await new Promise((resolve, reject) => {
        this.$refs.majorInfo.validate((valid, done) => {
          if (valid) {
            resolve();
            done();
          } else {
            this.tabsIndex = '1';
          }
        });
      });
      let validData3 = new Promise((resolve, reject) => {
        this.$refs.purchaseInfo.validate((valid, done) => {
          if (valid) {
            resolve();
            done();
          } else {
            this.tabsIndex = '2';
          }
        });
      });
      Promise.all([validData1, validData2, validData3]).then(() => {
        delete this.form.PICTURE;
        delete this.form.INSPECTION;
        delete this.form.CERT;
        this.form.status = 1;
        this.form.categoryCode = 'STEELMESH';
        this.form.equipmentTool = {
          inventoryId: this.form.inventoryId,
          areaId: this.form.areaId,
          suitEquipmentId: this.form.suitEquipmentId,
          procurementPrice: this.form.procurementPrice,
          partnerId: this.form.partnerId,
          keepAccountDate: this.form.keepAccountDate,
          enabledDate: this.form.enabledDate,
          elasticStdValue: this.form.elasticStdValue,
          elasticWarnValue: this.form.elasticWarnValue
        };
        add(this.form).then((res) => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: res.data.msg
          });
          this.showDialog = false;
        });
      });
    },
    /**
     * 查看详情数据
     */
    rowView(row) {
      this.showDialog = true;
      this.dialogTitle = '详情';
      this.$nextTick(() => {
        this.$refs.basicInfo.allDisabled = true;
        this.$refs.majorInfo.allDisabled = true;
        this.$refs.purchaseInfo.allDisabled = true;
        this.$refs.enclosureInfo.allDisabled = true;
        this.$refs.maintenanceInfo.allDisabled = true;
      });
      getDetail(row.id).then((res) => {
        this.form = res.data.data;
        if (this.form.status) {
          this.form.status = this.form.status.toString();
          this.form.keepAccountDate = this._get(res, 'data.data.equipmentTool.keepAccountDate', '');
          this.form.enabledDate = this._get(res, 'data.data.equipmentTool.enabledDate', '');
          this.form.inventoryId = this._get(res, 'data.data.equipmentTool.inventoryId', '');
          this.form.inventoryName = this._get(res, 'data.data.equipmentTool.inventoryName', '');
          getAreaTreeByInventoryId({ inventoryId: this.form.inventoryId }).then((res) => {
            this.itemData = (res.data.data || []).map((item) => {
              return item;
            });
            const column = this.findObject(this.majorInfoOption.column, 'areaId');
            column.dicData = this.itemData;
          });
          this.form.areaId = this._get(res, 'data.data.equipmentTool.areaId', '');
          this.form.suitEquipmentName = this._get(res, 'data.data.equipmentTool.suitEquipmentName', '');
          this.form.elasticStdValue = this._get(res, 'data.data.equipmentTool.elasticStdValue', '');
          this.form.elasticWarnValue = this._get(res, 'data.data.equipmentTool.elasticWarnValue', '');
          this.form.procurementPrice = this._get(res, 'data.data.equipmentTool.procurementPrice', '');
          this.form.partnerId = this._get(res, 'data.data.equipmentTool.partnerId', '');
          this.form.supplierName = this._get(res, 'data.data.equipmentTool.supplierName', '');
          this._forEach(this.form.equipmentAttachmentList, (item) => {
            if (item.attachmentType === 'PICTURE') {
              this.form.PICTURE = item.link;
            } else if (item.attachmentType === 'INSPECTION') {
              this.form.INSPECTION = item.link;
              this.form.INSPECTIONNAME = item.originalName;
            } else if (item.attachmentType === 'CERT') {
              this.form.CERT = item.link;
              this.form.CERTNAME = item.originalName;
            }
          });
        }
      });
    },
    rowUpdate(row) {
      this.showDialog = true;
      this.dialogTitle = '编辑';
      this.$nextTick(() => {
        this.$refs.basicInfo.allDisabled = false;
        this.$refs.majorInfo.allDisabled = false;
        this.$refs.purchaseInfo.allDisabled = false;
        this.$refs.enclosureInfo.allDisabled = false;
        this.$refs.maintenanceInfo.allDisabled = false;
      });
      getDetail(row.id).then((res) => {
        this.form = res.data.data;
        this.form.status = this.form.status.toString();
        this.form.keepAccountDate = this._get(res, 'data.data.equipmentTool.keepAccountDate', '');
        this.form.enabledDate = this._get(res, 'data.data.equipmentTool.enabledDate', '');
        this.form.inventoryId = this._get(res, 'data.data.equipmentTool.inventoryId', '');
        this.form.inventoryName = this._get(res, 'data.data.equipmentTool.inventoryName', '');
        getAreaTreeByInventoryId({ inventoryId: this.form.inventoryId }).then((res) => {
          this.itemData = (res.data.data || []).map((item) => {
            return item;
          });
          const column = this.findObject(this.majorInfoOption.column, 'areaId');
          column.dicData = this.itemData;
        });
        this.form.areaId = this._get(res, 'data.data.equipmentTool.areaId', '');
        this.form.suitEquipmentName = this._get(res, 'data.data.equipmentTool.suitEquipmentName', '');
        this.form.elasticStdValue = this._get(res, 'data.data.equipmentTool.elasticStdValue', '');
        this.form.elasticWarnValue = this._get(res, 'data.data.equipmentTool.elasticWarnValue', '');
        this.form.procurementPrice = this._get(res, 'data.data.equipmentTool.procurementPrice', '');
        this.form.partnerId = this._get(res, 'data.data.equipmentTool.partnerId', '');
        this.form.supplierName = this._get(res, 'data.data.equipmentTool.supplierName', '');
        this._forEach(this.form.equipmentAttachmentList, (item) => {
          if (item.attachmentType === 'PICTURE') {
            this.pictureList = [{ name: item.originalName, url: item.link }];
          } else if (item.attachmentType === 'INSPECTION') {
            this.inspectionList = [{ name: item.originalName, url: item.link }];
          } else if (item.attachmentType === 'CERT') {
            this.certList = [{ name: item.originalName, url: item.link }];
          }
        });
      });
    },
    rowDel(row) {
      if (row.status === 4) {
        this.$message({
          type: 'warning',
          message: '当前钢网领用中，不可删除！'
        });
        return;
      }
      if (row.status === 1 && row.timesUsed && Number(row.timesUsed) > 0) {
        this.$message({
          type: 'warning',
          message: '当前钢网存在使用记录且状态为正常，不可删除！'
        });
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove([row.id]);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    closeDialog() {
      this.$refs.basicInfo.resetFields();
      this.$refs.majorInfo.resetFields();
      this.$refs.purchaseInfo.resetFields();
      this.$refs.enclosureInfo.resetFields();
      this.$refs.maintenanceInfo.resetFields();
      this.form = {};
      this.pictureList = [];
      this.inspectionList = [];
      this.certList = [];
      this.tabsIndex = '1';
    },
    handleDownload(link) {
      window.open(`${link}`);
    },
    handleExport() {
      this.exportData = this.data;
      this.exprotVisible = true;
    },
    handleClose(val) {
      this.exprotVisible = false;
      this.data = this.exportData.splice(0, this.page.pageSize);
    },
    handleSelectData(val) {
      let current = 1;
      let pageSize = this.page.pageSize;
      if (val === 'all') {
        // 接口返回上限500条数据
        pageSize = 500;
      } else {
        current = this.page.currentPage;
      }
      this.btnLoading = true;
      getSteelMeshList(current, pageSize, Object.assign(this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.exportData = data.records;
        this.btnLoading = false;
      });
    },
    openPreview(index = 0, link) {
      this.$ImagePreview([{ url: link }], index, {
        closeOnClickModal: false
      });
    },
    handleEnableOrDisable(row, btnType) {
      if (btnType === 'enable') {
        this.$confirm('是否确定启用这条数据?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          equipmentEnable(row.id).then(
            () => {
              this.onLoad(this.page);
              this.$message({
                type: 'success',
                message: '已启用!'
              });
            },
            (error) => {}
          );
        });
      } else {
        if (row.status === 4) {
          this.$message({
            type: 'warning',
            message: '当前钢网领用中，不可禁用!'
          });
          return;
        }
        if (row.status === 1) {
          this.$confirm('是否确定禁用这条数据?', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            equipmentDisable(row.id).then(
              () => {
                this.onLoad(this.page);
                this.$message({
                  type: 'success',
                  message: '已禁用!'
                });
              },
              (error) => {}
            );
          });
        } else {
          this.$message({
            type: 'warning',
            message: '当前钢网不可禁用!'
          });
          return;
        }
      }
    }
  }
};
</script>
